package com.ndp.fb.mq.service.schedulerservice;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.constant.ConfigConst;
import com.ndp.fb.mongo.api.AdGroupStatsHistoryMongoService;
import com.ndp.fb.mq.api.producer.RocketMqProducerService;
import com.ndp.fb.mq.api.service.schedulerservice.ScanAdGroupStatisticsService;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.util.DateUtil;
import com.ndp.fb.util.ThreadPool;
import com.ndp.fb.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 定时扫描AdGroup统计数据
 */
@Service
public class ScanAdGroupStatisticsServiceImpl implements ScanAdGroupStatisticsService {

    private static Logger logger = LoggerFactory.getLogger(ScanAdGroupStatisticsServiceImpl.class);
    @Reference
    private AdGroupStatsHistoryMongoService adGroupStatsHistoryMongoService;
    @Autowired
    private RedisClient redisClient;

    @Autowired
    private RocketMqProducerService rocketMqProducerService;

    @Override
    public void findChangedAdGroupAndNotice() {
    	ThreadPool.execute(() -> {
            Object lastScanTime = redisClient.get(CommonConstants.LAST_ADGROUP_STATISTICS_SCAN_TIME);
            // 零时区当前时间
            Date nowUTCDate = DateUtil.getNowUTCDate();
            Date startTime =DateUtil.getUtcDate(lastScanTime, nowUTCDate);
            Date endTime = nowUTCDate;
            redisClient.set(CommonConstants.LAST_ADGROUP_STATISTICS_SCAN_TIME, endTime);
            logger.info("扫描AdGroup统计数据，Mongo查询开始，查询参数，startTime=" + startTime + ",endTime=" + endTime);
            long start = System.currentTimeMillis();
            List adGroupIds = adGroupStatsHistoryMongoService.findChangedAdGroupIds(startTime, endTime);
            int size = adGroupIds.size();
            long end = System.currentTimeMillis();
            logger.info("扫描AdGroup统计数据，Mongo查询结束，查询花费时间" + (end - start) + "毫秒，查询到的条数：" + size + "条");
            if (!CollectionUtils.isEmpty(adGroupIds)) {
                logger.info("扫描AdGroup统计数据，RocketMQ消息发送开始");
                for (int i = 0; i < size; i++) {
                    Long adGroupId = (Long) adGroupIds.get(i);
                    // RocketMQ消息发送
                    String topicName = ConfigConst.MQ_SERVICES_RULE_SCRIPT_TOPIC;
                    String tagName = topicName + ConfigConst.ROCKETMQ_TOPIC_TAG_SPLIT + ConfigConst.MQ_SERVICES_RULE_SCRIPT_ADGROUP_CHANGED_TAG;
                    String keys = UUID.get();
                    rocketMqProducerService.sendMessage(topicName, tagName, keys, adGroupId);
                }
                logger.info("扫描AdGroup统计数据，RocketMQ消息发送结束，花费时间" + (System.currentTimeMillis() - end) + "毫秒");
            }
        });
        
    }
}
